#include <dspSimulator/command/continue.h>
#include <dspSimulator/dspSimulator/dspSimulator.h>

void ContinueCommand::execute(std::string command) {
    auto dspSimulator = dynamic_cast<DSPSimulator *>(m_simulator);
    if (dspSimulator == nullptr) {
        fatalMacro("该模拟器对象不为dsp模拟器对象!");
    }
    auto breakPoints = dspSimulator->m_breakPoints;

    auto endIter = breakPoints.end();
    bool flag = false;
    while (!flag) {
        dspSimulator->execute(m_executePacket);
        m_executePacket = dspSimulator->decode(dspSimulator->fetch());
        dspSimulator->m_numOfInstruction += m_executePacket.size();
        for (auto &instruction: m_executePacket) {
            if (breakPoints.find(instruction->getInstructionAddress()) != endIter) {
                flag = true;
                break;
            }
        }
    }
    // 打印指令执行包信息
    bool isFirstInstruction = true;
    u64 offset = m_executePacket.size();
    for (auto &inst: m_executePacket) {
        if (isFirstInstruction) {
            fprintf(stdout, ">> %08lX : %s\t t=%lu\n", inst->getInstructionAddress(),
                    inst->toString().c_str(), dspSimulator->m_numOfInstruction - offset + 1);
            isFirstInstruction = false;
        } else {
            fprintf(stdout, ">> %08lX : || %s\t t=%lu\n", inst->getInstructionAddress(),
                    inst->toString().c_str(), dspSimulator->m_numOfInstruction - offset + 1);
        }
        --offset;
    }
}

std::shared_ptr<ContinueCommand>
ContinueCommand::get(Simulator* dspSimulator, std::vector<std::shared_ptr<Instruction>> &executePacket) {
    static std::shared_ptr<ContinueCommand> continueCommand;
    if (continueCommand == nullptr) {
        continueCommand = std::make_shared<ContinueCommand>(dspSimulator, executePacket);
    }
    return continueCommand;
}
